"""
性能监控和查询优化中间件
"""
import time
import logging
from django.db import connection, reset_queries
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
from .monitoring import performance_monitor, error_collector

logger = logging.getLogger(__name__)


class QueryCountMiddleware(MiddlewareMixin):
    """数据库查询计数中间件（仅用于开发环境）"""
    
    def process_request(self, request):
        """请求开始时重置查询计数"""
        if hasattr(settings, 'DEBUG') and settings.DEBUG:
            reset_queries()
            request._query_start_time = time.time()
    
    def process_response(self, request, response):
        """响应结束时记录查询统计"""
        if hasattr(settings, 'DEBUG') and settings.DEBUG:
            if hasattr(request, '_query_start_time'):
                query_count = len(connection.queries)
                query_time = time.time() - request._query_start_time
                
                # 如果查询次数过多，记录警告
                if query_count > 20:
                    logger.warning(
                        f'高查询数检测: {request.path} - {query_count}次查询 - 耗时: {query_time:.3f}s'
                    )
                
                # 记录到性能监控
                if query_count > 0:
                    performance_monitor.record_api_request(
                        endpoint=request.path,
                        method=request.method,
                        duration=query_time,
                        status_code=response.status_code,
                        user_id=getattr(request.user, 'id', None) if hasattr(request, 'user') else None
                    )
        
        return response


class PerformanceMonitoringMiddleware(MiddlewareMixin):
    """性能监控中间件"""
    
    def process_request(self, request):
        """记录请求开始时间"""
        request._start_time = time.time()
    
    def process_response(self, request, response):
        """记录请求耗时"""
        if hasattr(request, '_start_time'):
            duration = time.time() - request._start_time
            
            # 只记录API请求（排除静态文件等）
            if request.path.startswith('/api/'):
                performance_monitor.record_api_request(
                    endpoint=request.path,
                    method=request.method,
                    duration=duration,
                    status_code=response.status_code,
                    user_id=getattr(request.user, 'id', None) if hasattr(request, 'user') else None
                )
        
        return response

